'''
Description: description
Author: 
LastEditors: M
'''
import time,shutil,os

import compoments.utils as U
import compoments.config as CFG
from compoments.params import try_load_params



class T_task():
    """
    用于测试的task 
    """

    def load_params_and_run(self,task_group_nickname):
        U.print_with_time("开始任务:\n\t",self)
        if os.getcwd()!=CFG.PROJECT_DIR:
            os.chdir(CFG.PROJECT_DIR)
        exe_cmd = "python piker/compoments/test_task.py"

        log_file = f"piker/logs/{task_group_nickname}/task_{int(time.time())}.log"

        U.try_makedirs(os.path.dirname(log_file))

        exe_cmd = f"{exe_cmd}"
        
        s = os.system(exe_cmd)
        if s==0:
            print(self,"\n\trunning ok")
        else:
            print(self,f"\n\texit with code {s}")
    def __rper__(self):
        return "sample task"
    def __str__(self):
        return "sample task"

class PikerTask(T_task):
    id=None 
    params_fp_from:str=None 
    params_fp_dest:str=None 
    exe_cmd:str=None 
    def __init__(self,id,p_to_fp,p_from_fp) -> None:
        self.id = id
        self.params_fp_dest=p_to_fp
        self.params_fp_from=p_from_fp
        exe_cmd_key = CFG.exe_command_key
        P = try_load_params(self.params_fp_from)
        self.exe_cmd = P[exe_cmd_key]
        print("添加任务",self)

    def load_params_and_run(self, task_group_nickname):
        """
        将参数文件放到指定的位置
        """
        U.print_with_time("开始任务:\n\t",self)
        shutil.copyfile(self.params_fp_from,self.params_fp_dest)
        if os.getcwd()!=CFG.PROJECT_DIR:
            os.chdir(CFG.PROJECT_DIR)
        params_name = os.path.basename(self.params_fp_from).split('.')[0]

        log_file = f"piker/logs/{task_group_nickname}/task_{params_name}.log"

        U.try_makedirs(os.path.dirname(log_file))

        exe_cmd = f"{self.exe_cmd} > {log_file}"

        s = os.system(exe_cmd)
        if s==0:
            print(self,"\n\trunning ok")
        else:
            print(self,f"\n\texit with code {s}")
    def __repr__(self) -> str:
        return f"task({self.id}) params from {self.params_fp_from}"
    def __str__(self) -> str:
        return f"task({self.id}) params from {self.params_fp_from}"